package jnpf.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import jnpf.base.ActionResult;
import jnpf.base.UserInfo;
import jnpf.base.entity.VisualdevEntity;
import jnpf.base.service.VisualdevService;
import jnpf.base.util.VisualUtils;
import jnpf.base.vo.PageListVO;
import jnpf.base.vo.PaginationVO;
import jnpf.engine.entity.FlowTaskEntity;
import jnpf.engine.enums.FlowStatusEnum;
import jnpf.engine.service.FlowTaskService;
import jnpf.entity.ZXGL_XiangMuLiXiang_MingXiEntity;
import jnpf.entity.ZXGL_XiangMuZhiPaiXieBanRenMingXiBiaoEntity;
import jnpf.entity.ZXGL_XiangMuZhiPaiXieBanRenZhuBiaoEntity;
import jnpf.exception.DataException;
import jnpf.exception.WorkFlowException;
import jnpf.generater.util.GeneraterSwapUtil;
import jnpf.model.common.ZXGL_FlowWriteBack;
import jnpf.model.common.ZXGL_XzbmLeaders;
import jnpf.model.zxgl_xiangmuzhipaixiebanrenzhubiao.*;
import jnpf.service.ZXGL_OrganizeService;
import jnpf.service.ZXGL_XiangMuLiXiang_MingXiService;
import jnpf.service.ZXGL_XiangMuZhiPaiXieBanRenMingXiBiaoService;
import jnpf.service.ZXGL_XiangMuZhiPaiXieBanRenZhuBiaoService;
import jnpf.util.JsonUtil;
import jnpf.util.RandomUtil;
import jnpf.util.UserProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * ZXGL_XiangMuZhiPaiXieBanRenZhuBiao
 *
 * @版本： V2.0
 * @版权： 河北交投智能交通技术有限责任公司
 * @作者： 数字交投项目组
 * @日期： 2025-04-10
 */
@Slf4j
@RestController
@Api(tags = "ZXGL_XiangMuZhiPaiXieBanRenZhuBiao", value = "zxgl")
@RequestMapping("/ZXGL_XiangMuZhiPaiXieBanRenZhuBiao")
public class ZXGL_XiangMuZhiPaiXieBanRenZhuBiaoController {


    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private UserProvider userProvider;

    @Autowired
    private VisualdevService visualdevService;

    @Autowired
    private FlowTaskService flowTaskService;

    @Autowired
    private ZXGL_XiangMuZhiPaiXieBanRenZhuBiaoService zXGL_XiangMuZhiPaiXieBanRenZhuBiaoService;

    @Autowired
    private ZXGL_XiangMuZhiPaiXieBanRenMingXiBiaoService zXGL_XiangMuZhiPaiXieBanRenMingXiBiaoService;

    @Autowired
    private ZXGL_OrganizeService zxglOrganizeService;

    @Autowired
    private ZXGL_XiangMuLiXiang_MingXiService zxglXiangMuLiXiangMingXiService;


    /**
     * 列表
     *
     * @param zXGL_XiangMuZhiPaiXieBanRenZhuBiaoPagination
     * @return
     */
    @PostMapping("/getList")
    public ActionResult list(@RequestBody ZXGL_XiangMuZhiPaiXieBanRenZhuBiaoPagination zXGL_XiangMuZhiPaiXieBanRenZhuBiaoPagination) throws IOException {
        List<ZXGL_XiangMuZhiPaiXieBanRenZhuBiaoEntity> list = zXGL_XiangMuZhiPaiXieBanRenZhuBiaoService.getList(zXGL_XiangMuZhiPaiXieBanRenZhuBiaoPagination);
        //处理id字段转名称，若无需转或者为空可删除
        for (ZXGL_XiangMuZhiPaiXieBanRenZhuBiaoEntity entity : list) {
            entity.setDepartmentManagerXzbm(generaterSwapUtil.userSelectValues(entity.getDepartmentManagerXzbm()));
            entity.setXzbm(generaterSwapUtil.comSelectValues(entity.getXzbm()));
            entity.setXzr(generaterSwapUtil.userSelectValues(entity.getXzr()));
        }
        List<ZXGL_XiangMuZhiPaiXieBanRenZhuBiaoListVO> listVO = JsonUtil.getJsonToList(list, ZXGL_XiangMuZhiPaiXieBanRenZhuBiaoListVO.class);
        for (ZXGL_XiangMuZhiPaiXieBanRenZhuBiaoListVO zXGL_XiangMuZhiPaiXieBanRenZhuBiaoVO : listVO) {
        }


        for (ZXGL_XiangMuZhiPaiXieBanRenZhuBiaoListVO vo : listVO) {
            FlowTaskEntity flowTaskEntity = flowTaskService.getInfoSubmit(vo.getId());
            if (flowTaskEntity != null) {
                vo.setFlowState(flowTaskEntity.getStatus());
            } else {
                vo.setFlowState(null);
            }
        }

        PageListVO vo = new PageListVO();
        vo.setList(listVO);
        PaginationVO page = JsonUtil.getJsonToBean(zXGL_XiangMuZhiPaiXieBanRenZhuBiaoPagination, PaginationVO.class);
        vo.setPagination(page);
        return ActionResult.success(vo);
    }


    /**
     * 创建
     *
     * @param zXGL_XiangMuZhiPaiXieBanRenZhuBiaoCrForm
     * @return
     */
    @PostMapping
    @Transactional
    public ActionResult create(@RequestBody @Valid ZXGL_XiangMuZhiPaiXieBanRenZhuBiaoCrForm zXGL_XiangMuZhiPaiXieBanRenZhuBiaoCrForm) throws DataException {
        String visualId = "680057614092023749";
        VisualdevEntity visualdevEntity = visualdevService.getInfo(visualId);
        String mainId = RandomUtil.uuId();
        UserInfo userInfo = userProvider.get();
        ZXGL_XiangMuZhiPaiXieBanRenZhuBiaoEntity entity = JsonUtil.getJsonToBean(zXGL_XiangMuZhiPaiXieBanRenZhuBiaoCrForm, ZXGL_XiangMuZhiPaiXieBanRenZhuBiaoEntity.class);
        entity.setId(mainId);

        // reggion 赋值部门领导和负责人
        ZXGL_XzbmLeaders leaders = zxglOrganizeService.getXzbmLeaders(entity.getXzbm());
        entity.setDepartmentManagerXzbm(leaders.getDepartmentManagerXzbm());
        entity.setDepartmentHeadleaderXzbm(leaders.getDepartmentHeadleaderXzbm());
        // endreion

        zXGL_XiangMuZhiPaiXieBanRenZhuBiaoService.save(entity);
        List<ZXGL_XiangMuZhiPaiXieBanRenMingXiBiaoEntity> ZXGL_XiangMuZhiPaiXieBanRenMingXiBiaoList = JsonUtil.getJsonToList(zXGL_XiangMuZhiPaiXieBanRenZhuBiaoCrForm.getZxgl_xiangmuzhipaixiebanrenmingxibiaoList(), ZXGL_XiangMuZhiPaiXieBanRenMingXiBiaoEntity.class);

        for (ZXGL_XiangMuZhiPaiXieBanRenMingXiBiaoEntity entitys : ZXGL_XiangMuZhiPaiXieBanRenMingXiBiaoList) {
            entitys.setId(RandomUtil.uuId());
            entitys.setMainid(entity.getId());
            zXGL_XiangMuZhiPaiXieBanRenMingXiBiaoService.save(entitys);
        }
        if (FlowStatusEnum.submit.getMessage().equals(zXGL_XiangMuZhiPaiXieBanRenZhuBiaoCrForm.getStatus())) {
            try {
                VisualUtils.submitFlowTask(visualdevEntity, mainId, zXGL_XiangMuZhiPaiXieBanRenZhuBiaoCrForm, userInfo, zXGL_XiangMuZhiPaiXieBanRenZhuBiaoCrForm.getCandidateList());
            } catch (WorkFlowException e) {
                e.printStackTrace();
            }
            return ActionResult.success("提交成功，请耐心等待");
        }
        return ActionResult.success("保存成功");
    }


    /**
     * 信息
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public ActionResult<ZXGL_XiangMuZhiPaiXieBanRenZhuBiaoInfoVO> info(@PathVariable("id") String id) {
        ZXGL_XiangMuZhiPaiXieBanRenZhuBiaoEntity entity = zXGL_XiangMuZhiPaiXieBanRenZhuBiaoService.getInfo(id);
        ZXGL_XiangMuZhiPaiXieBanRenZhuBiaoInfoVO vo = JsonUtil.getJsonToBean(entity, ZXGL_XiangMuZhiPaiXieBanRenZhuBiaoInfoVO.class);

        //子表
        List<ZXGL_XiangMuZhiPaiXieBanRenMingXiBiaoEntity> ZXGL_XiangMuZhiPaiXieBanRenMingXiBiaoList = zXGL_XiangMuZhiPaiXieBanRenZhuBiaoService.GetZXGL_XiangMuZhiPaiXieBanRenMingXiBiaoList(id);
        for (ZXGL_XiangMuZhiPaiXieBanRenMingXiBiaoEntity zxgl_xiangmuzhipaixiebanrenmingxibiaoEntity : ZXGL_XiangMuZhiPaiXieBanRenMingXiBiaoList) {

        }
        vo.setZXGL_XiangMuZhiPaiXieBanRenMingXiBiaoList(JsonUtil.getJsonToList(ZXGL_XiangMuZhiPaiXieBanRenMingXiBiaoList, ZXGL_XiangMuZhiPaiXieBanRenMingXiBiaoModel.class));
        //副表
        return ActionResult.success(vo);
    }


    /**
     * 更新
     *
     * @param id
     * @return
     */
    @PutMapping("/{id}")
    @Transactional
    public ActionResult update(@PathVariable("id") String id, @RequestBody @Valid ZXGL_XiangMuZhiPaiXieBanRenZhuBiaoUpForm zXGL_XiangMuZhiPaiXieBanRenZhuBiaoUpForm) throws DataException {
        String visualId = "680057614092023749";
        VisualdevEntity visualdevEntity = visualdevService.getInfo(visualId);
        UserInfo userInfo = userProvider.get();
        ZXGL_XiangMuZhiPaiXieBanRenZhuBiaoEntity entity = zXGL_XiangMuZhiPaiXieBanRenZhuBiaoService.getInfo(id);
        if (entity != null) {
            ZXGL_XiangMuZhiPaiXieBanRenZhuBiaoEntity subentity = JsonUtil.getJsonToBean(zXGL_XiangMuZhiPaiXieBanRenZhuBiaoUpForm, ZXGL_XiangMuZhiPaiXieBanRenZhuBiaoEntity.class);

            // reggion 赋值部门领导和负责人
            ZXGL_XzbmLeaders leaders = zxglOrganizeService.getXzbmLeaders(entity.getXzbm());
            entity.setDepartmentManagerXzbm(leaders.getDepartmentManagerXzbm());
            entity.setDepartmentHeadleaderXzbm(leaders.getDepartmentHeadleaderXzbm());
            // endreion

            zXGL_XiangMuZhiPaiXieBanRenZhuBiaoService.update(id, subentity);

//            QueryWrapper<ZXGL_XiangMuZhiPaiXieBanRenMingXiBiaoEntity> ZXGL_XiangMuZhiPaiXieBanRenMingXiBiaoqueryWrapper = new QueryWrapper<>();
//            ZXGL_XiangMuZhiPaiXieBanRenMingXiBiaoqueryWrapper.lambda().eq(ZXGL_XiangMuZhiPaiXieBanRenMingXiBiaoEntity::getMainid, entity.getId());
//            zXGL_XiangMuZhiPaiXieBanRenMingXiBiaoService.remove(ZXGL_XiangMuZhiPaiXieBanRenMingXiBiaoqueryWrapper);

            List<ZXGL_XiangMuZhiPaiXieBanRenMingXiBiaoEntity> ZXGL_XiangMuZhiPaiXieBanRenMingXiBiaoList = JsonUtil.getJsonToList(zXGL_XiangMuZhiPaiXieBanRenZhuBiaoUpForm.getZxgl_xiangmuzhipaixiebanrenmingxibiaoList(), ZXGL_XiangMuZhiPaiXieBanRenMingXiBiaoEntity.class);
            for (ZXGL_XiangMuZhiPaiXieBanRenMingXiBiaoEntity entitys : ZXGL_XiangMuZhiPaiXieBanRenMingXiBiaoList) {
                if (StrUtil.isNotEmpty(entitys.getXmid())) {
                    zXGL_XiangMuZhiPaiXieBanRenMingXiBiaoService.updateById(entitys);
                } else {
                    entitys.setId(RandomUtil.uuId());
                    entitys.setMainid(entity.getId());
                    zXGL_XiangMuZhiPaiXieBanRenMingXiBiaoService.save(entitys);
                }
            }


            if (FlowStatusEnum.submit.getMessage().equals(zXGL_XiangMuZhiPaiXieBanRenZhuBiaoUpForm.getStatus())) {
                try {
                    VisualUtils.submitFlowTask(visualdevEntity, id, subentity, userInfo, zXGL_XiangMuZhiPaiXieBanRenZhuBiaoUpForm.getCandidateList());
                } catch (WorkFlowException e) {
                    e.printStackTrace();
                }
                return ActionResult.success("提交成功，请耐心等待");
            }
            return ActionResult.success("更新成功");
        } else {
            return ActionResult.fail("更新失败，数据不存在");
        }
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    @Transactional
    public ActionResult delete(@PathVariable("id") String id) {
        ZXGL_XiangMuZhiPaiXieBanRenZhuBiaoEntity entity = zXGL_XiangMuZhiPaiXieBanRenZhuBiaoService.getInfo(id);
        if (entity != null) {
            FlowTaskEntity taskEntity = flowTaskService.getInfoSubmit(id);
            if (taskEntity != null) {
                try {
                    flowTaskService.delete(taskEntity);
                } catch (WorkFlowException e) {
                    e.printStackTrace();
                }
            }
            zXGL_XiangMuZhiPaiXieBanRenZhuBiaoService.delete(entity);
            QueryWrapper<ZXGL_XiangMuZhiPaiXieBanRenMingXiBiaoEntity> queryWrapperZXGL_XiangMuZhiPaiXieBanRenMingXiBiao = new QueryWrapper<>();
            queryWrapperZXGL_XiangMuZhiPaiXieBanRenMingXiBiao.lambda().eq(ZXGL_XiangMuZhiPaiXieBanRenMingXiBiaoEntity::getMainid, entity.getId());
            zXGL_XiangMuZhiPaiXieBanRenMingXiBiaoService.remove(queryWrapperZXGL_XiangMuZhiPaiXieBanRenMingXiBiao);

        }
        return ActionResult.success("删除成功");
    }

    @PostMapping("/flowWriteBack")
    @Transactional
    public ActionResult flowWriteBack(@RequestBody ZXGL_FlowWriteBack flowWriteBack) {
        log.info("flowWriteBack:==========>" + flowWriteBack);
        ZXGL_XiangMuZhiPaiXieBanRenZhuBiaoEntity entity = zXGL_XiangMuZhiPaiXieBanRenZhuBiaoService.getById(flowWriteBack.getTaskId());
        if (entity != null) {
            List<ZXGL_XiangMuZhiPaiXieBanRenMingXiBiaoEntity> list = zXGL_XiangMuZhiPaiXieBanRenZhuBiaoService.GetZXGL_XiangMuZhiPaiXieBanRenMingXiBiaoList(flowWriteBack.getTaskId());
            if (list != null && list.size() > 0) {
                List<String> xmids = list.stream().map(ZXGL_XiangMuZhiPaiXieBanRenMingXiBiaoEntity::getXmid).distinct().collect(Collectors.toList());
                QueryWrapper<ZXGL_XiangMuLiXiang_MingXiEntity> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().in(ZXGL_XiangMuLiXiang_MingXiEntity::getId, xmids);
                List<ZXGL_XiangMuLiXiang_MingXiEntity> models = zxglXiangMuLiXiangMingXiService.list(queryWrapper);
                if (models != null && models.size() > 0) {
                    for (ZXGL_XiangMuZhiPaiXieBanRenMingXiBiaoEntity entry : list) {
                        ZXGL_XiangMuLiXiang_MingXiEntity model = models.stream().filter(o -> o.getId().equals(entry.getXmid())).findFirst().orElse(null);
                        if (model != null) {
                            if (StrUtil.isEmpty(model.getXzr())) {
                                model.setXzr(entry.getXzr());
                            } else {
                                String xzrids = model.getXzr() + "," + entry.getXzr();
                                //去重
                                Set<String> set = new HashSet<>(Arrays.asList(xzrids.split(",")));
                                xzrids = String.join(",", set);
                                model.setXzr(xzrids);
                            }
                        }
                    }
                    log.info("models:==========>" + models);
                    zxglXiangMuLiXiangMingXiService.updateBatchById(models);
                }
            }
        }
        return ActionResult.success("回写成功");
    }
}
